package com.gitee.zjbqdzq;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.RuntimeUtil;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class Main1 {

    private static final Logger log = LoggerFactory.getLogger(Main1.class);

    @Getter
    @Setter
    static class Commander {
        @Parameter(names = {"--folder", "-f"}, description = "视频文件所在文件夹", required = true)
        private String saveFolder;
        @Parameter(names = {"--help", "-h"})
        private boolean help = false;
    }

    public static void main(String[] args) {
        Commander commander = new Commander();
        JCommander jCommander = JCommander.newBuilder().addObject(commander).build();
        jCommander.parse(args);
        if (commander.help) {
            jCommander.usage();
            return;
        }
        extracted(commander);
    }

    private static void extracted(Commander commander) {
        String saveFolder = commander.getSaveFolder();
        File file = Paths.get(saveFolder).toFile();
        if (!BooleanUtil.and(file.exists(), file.isDirectory())) {
            log.info("文件夹{}不存在", saveFolder);
            return;
        }
        File[] obj = file.listFiles();
        List<String> filenameList = Arrays.stream(Objects.requireNonNullElse(obj, new File[0])).filter(File::isFile).map(File::getName).toList();

        filenameList.stream().map(v -> v.substring(0, v.lastIndexOf('.'))).map(name -> Paths.get(saveFolder, name)).forEach(Main1::mkdir);

        filenameList.stream().map(v -> Paths.get(saveFolder, v)).forEach(Main1::transform);
    }

    private static void transform(Path path) {
        String filename = path.toString();
        log.info(filename);
        String output = Paths.get(filename.substring(0, filename.lastIndexOf('.')), "output.m3u8").toString();
        Process ffmpeg = RuntimeUtil.exec("ffmpeg", "-i", filename, "-codec:", "copy", "-start_number", "0", "-hls_time", "10", "-hls_list_size", "0", "-f", "hls", output);
        try (BufferedReader reader = ffmpeg.inputReader()) {
            while ((reader.readLine()) != null) ;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        if (0 == ffmpeg.exitValue()) {
            log.info("{}转换完成", filename);
        } else {
            log.error("{}转换失败", filename);
        }
    }

    private static void mkdir(Path path) {
        File file = path.toFile();
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}
